﻿using MediatR;
using WarehouseManagement.Application.Command.WarehouseTypeCommand;
using WarehouseManagement.Domain.DTO.WarehouseType;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;
namespace WarehouseManagement.Application.CommandHandler.WareTypeCommandHandler
{
    public class ShowWareTypeCommandHandler:IRequestHandler<ShowWareTypeCommand,List<SelWareTypeDTO>>
    {
        private readonly IWareTypeRepository _waretype;

        public ShowWareTypeCommandHandler(IWareTypeRepository waretype)
        {
            _waretype = waretype;
        }

        public async Task<List<SelWareTypeDTO>> Handle(ShowWareTypeCommand request, CancellationToken cancellationToken)
        {
              List<SelWareTypeDTO> dtos = new List<SelWareTypeDTO>();

            if(request.id == 0)
            {
                var newtypes = (await _waretype.GetAll()).Where(x => x.IsDel == false).Select(x => new SelWareTypeDTO
                {
                    WarehouseCategoryId = x.WarehouseCategoryId,
                    WCTypeName = x.WCTypeName,
                    WCFatherType = x.WCFatherType,
                    WCTypeNumber = x.WCTypeNumber,
                }).ToList();
                dtos = newtypes;
                return dtos;
            }
            else
            {
                var types = (await _waretype.GetAll()).ToList();
                var parentId = request.id;
                List<SelWareTypeDTO> sel = BuildTree(types, request.id);
                dtos = sel;
                return dtos;
            }




        }

        // 递归构建分类树
        static List<SelWareTypeDTO> BuildTree(List<WarehouseCategory> categories, int parentId)
        {
            return categories
               .Where(c => c.WCFatherType == parentId && c.IsDel == false)
               .Select(c => new SelWareTypeDTO
               {
                   WarehouseCategoryId = c.WarehouseCategoryId,
                   WCTypeName = c.WCTypeName,
                   WCFatherType = c.WCFatherType // 递归构建子分类
               })
               .ToList();
        }
    }
}
